package com.fablesoft.projectdatacollect.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;

public class MainActivity extends FragmentActivity {

    private long mLastClickTime;
    private static final int BACKKEY_TIME = 2500;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView loginName = (TextView) findViewById(R.id.login_name);
        loginName.setText("欢迎您，" + MyApplication.getInstance().getUsername());
        View safeCampaignBtn = findViewById(R.id.safe_campaign_btn);
        View personnelRegisterBtn = findViewById(R.id.personnel_register_btn);
        safeCampaignBtn.setOnClickListener(mOnClickListener);
        personnelRegisterBtn.setOnClickListener(mOnClickListener);
    }

    private OnClickListener mOnClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.personnel_register_btn:
                    startActivity(new Intent(MainActivity.this, PersonnelRegisterNewActivity.class));
                    break;
                case R.id.safe_campaign_btn:
                    startActivity(new Intent(MainActivity.this, SafeCampaignNewActivity.class));
                    break;
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            if (isFastClick()) {
                android.os.Process.killProcess(android.os.Process.myPid());
                return super.onKeyDown(keyCode, event);
            } else {
                Toast.makeText(this,
                        getResources().getString(R.string.exit_hint),
                        Toast.LENGTH_SHORT).show();
                return false;
            }
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    private boolean isFastClick() {

        long currentTime = System.currentTimeMillis();

        long time = currentTime - mLastClickTime;
        if (0 < time && time < BACKKEY_TIME) {
            return true;
        }

        mLastClickTime = currentTime;
        return false;
    }

}
